package icmc.mmse;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.SeekBar;

public class MainActivity extends Activity {

	private String fileEmotion;
	private String pathFiles;
	private SeekBar seekBarPleasure;
	private SeekBar seekBarActiveness;
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_main);
        
        pathFiles = GetRoot()+"/icmc/mmse/files/";
        fileEmotion = "emotion.txt";
        this.seekBarPleasure = (SeekBar) findViewById(R.id.skb_pleasure);
        if (seekBarPleasure == null)
        	Log.d("TestMeu", "é NULL");
    	this.seekBarActiveness = (SeekBar) findViewById(R.id.skb_activeness);
    	
    	try {
			CreateFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
        
    }
    
    private String GetRoot() {
    	File root = android.os.Environment.getExternalStorageDirectory();
    	return root.toString();
    }
    
    private void CreateFile() throws IOException {
    	File file = new File(this.pathFiles);
    	
    	if (!file.isDirectory())
    		file.mkdirs();
    	

    	file = new File(this.pathFiles,this.fileEmotion);
        
        if(!file.exists()) {
        	
    		BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file, true));
    		
            byte[] data;
            
            data = new String("timestamp,pleasure,activeness\n").getBytes();

            fos.write(data);
            fos.flush();
            fos.close();	
            
        }

    }
    
    private void AppendData() throws IOException {
    	
    	Timestamp time = new Timestamp(System.currentTimeMillis());
    	String newData = (time.toString()+ "," + Integer.toString(this.seekBarPleasure.getProgress()) + "," +
    							Integer.toString(this.seekBarActiveness.getProgress()));
    	
    	PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(this.pathFiles+this.fileEmotion, true)));
        
    	out.println(newData);
    	out.close();
    	
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    public void sendData(View view) {
    	
    	try {
    		AppendData();
    	} catch (Exception ex) {
    	}
    	
    	
    }
    
}
